package com.example.miniioc.core;

import com.example.miniioc.annotations.Bean;
import com.example.miniioc.annotations.Configuration;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MiniApplicationContext {
    private final Map<String, Object> beanMap = new HashMap<>();

    public MiniApplicationContext(Class<?> configClass) {
        try {
            // 检查是否有 @Configuration
            if (!configClass.isAnnotationPresent(Configuration.class)) {
                throw new RuntimeException("配置类必须使用 @Configuration 注解");
            }

            Object configInstance = configClass.getDeclaredConstructor().newInstance();

            // 扫描配置类中的方法
            for (Method method : configClass.getDeclaredMethods()) {
                if (method.isAnnotationPresent(Bean.class)) {
                    Object bean = method.invoke(configInstance);
                    beanMap.put(method.getName(), bean);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("容器初始化失败", e);
        }
    }

    public Object getBean(String name) {
        return beanMap.get(name);
    }

    public <T> T getBean(String name, Class<T> clazz) {
        return clazz.cast(beanMap.get(name));
    }
}
